Imports System
Imports System.Xml
Imports System.io

Public Class BaseMsg

	'Public Enum TagTypes
	'	FIXML
	'	CPC
	'End Enum

	'Protected m_outertag As String = ""
	'Protected m_tagtype As TagTypes

	'Private Property TagOfType() As TagTypes
	'	Get
	'		Return m_tagtype
	'	End Get
	'	Set(ByVal Value As TagTypes)
	'		m_tagtype = Value
	'	End Set
	'End Property

	Private m_cpcint As CPCInterface
	Private m_uid As String = ""
	Private m_iscpc As Boolean = True

    Protected m_prodid As String
	Protected m_undlyid As String
	Protected m_undly_sectyp As String
	Protected m_undly_mmy As String
	Protected m_reqtype As String
	Protected m_resptype As String
	'Protected m_username As String
	Protected m_reqtyp As String
	Protected m_secTyp As String
	Public ShowXML As Boolean = True

	Protected m_errmsg As String

#Region "Properties"

	Public Sub SetReqTyp(ByVal sectyp As String)
		If (sectyp = "FUT") Then
			ReqTyp = "104"
		ElseIf sectyp = "OOF" Then
			ReqTyp = "101"
		Else
			ReqTyp = "102"
		End If
		m_secTyp = sectyp
	End Sub

	Public Property SecTyp() As String
		Get
			If (m_secTyp = "MLEG") Then
				Return Globals.GetSecTyp(m_undlyid)
			End If
			Return m_secTyp
		End Get
		Set(ByVal value As String)
			m_secTyp = value
		End Set
	End Property

	Public Property ProductID() As String
		Get
			Return m_prodid
		End Get
		Set(ByVal Value As String)
			m_prodid = Value
		End Set
	End Property

	Public Property UndlyID() As String
		Get
			Return m_undlyid
		End Get
		Set(ByVal Value As String)
			m_undlyid = Value
		End Set
	End Property

	Public Property UndlySecTyp() As String
		Get
			Return m_undly_sectyp
		End Get
		Set(ByVal Value As String)
			m_undly_sectyp = Value
		End Set
	End Property

	Public Property UndlyMMY() As String
		Get
			Return m_undly_mmy
		End Get
		Set(ByVal Value As String)
			m_undly_mmy = Value
		End Set
	End Property

	Protected Property RequestType() As String
		Get
			Return m_reqtype
		End Get
		Set(ByVal Value As String)
			m_reqtype = Value
		End Set
	End Property

	Public Property ReqTyp() As String
		Get
			Return m_reqtyp
		End Get
		Set(ByVal value As String)
			m_reqtyp = value
		End Set
	End Property
	Protected Property ResponseType() As String
		Get
			Return m_resptype
		End Get
		Set(ByVal Value As String)
			m_resptype = Value
		End Set
	End Property

	Public ReadOnly Property ErrMsg() As String
		Get
			Return m_errmsg
		End Get
	End Property

	Protected Property IsCPC() As Boolean
		Get
			Return m_iscpc
		End Get
		Set(ByVal Value As Boolean)
			m_iscpc = Value
		End Set
	End Property

	Protected ReadOnly Property CPCI() As CPCInterface
		Get
			Return m_cpcint
		End Get
	End Property

	Protected ReadOnly Property UID() As String
		Get
			If m_uid = "" Then
				m_uid = timestamp()
			End If

			Return m_uid
		End Get
	End Property

	'Public Property UserName() As String
	'    Get
	'        Return m_username
	'    End Get
	'    Set(ByVal Value As String)
	'        m_username = Value
	'    End Set
	'End Property
#End Region

	Protected Sub ResetUID()
		m_uid = ""
	End Sub

	Public Sub New()
		m_cpcint = Globals.CPCInt
		m_cpcint.Reset()
	End Sub

	Public Function Submit() As Boolean
		m_errmsg = ""

		m_cpcint.Message = CallRequest()

		If m_cpcint.Message = "" Then
			Return False
		End If

		'Log.LogData("Sent:  " & m_cpcint.Message)
		If ShowXML Then
			Globals.SetSent(m_cpcint.Message)
		End If

		Dim dtSent As DateTime = DateTime.Now

		If (m_cpcint.SendMessage()) Then
			'Log.LogData("Reply: " & CPCI.ReplyMsg)

			LogData(dtSent)

			If ShowXML Then
				Globals.SetReply(m_cpcint.ReplyMsg)
			End If
			CallResponse()
			If m_errmsg = "" Then
				Return True
			Else
				Return False
			End If
		Else
			'm_cpcint.ReplyMsg = "no reply at all"
			LogData(dtSent)
		End If

		Return False

	End Function

	Private Sub LogData(ByVal dtSent As DateTime)
		Dim data As String = "<xml>" & vbCrLf
		data &= "<sent><time>" & dtSent.ToString() & "</time><data>"
		data &= m_cpcint.Message & "</data></sent>" & vbCrLf
		data &= "<response><time>" & dtSent.ToString() & "</time><data>"
		data &= m_cpcint.ReplyMsg & "</data></response></xml>" & vbCrLf

		Log.LogData(data, Me.RequestType)
	End Sub

	Private Function CallRequest() As String
		Dim rm As String

		Dim mem As New MemoryStream

		'Dim w As New Stream(mem)

		Dim xmlw As New XmlTextWriter(mem, System.Text.Encoding.UTF8)

		xmlw.WriteStartDocument()

		If IsCPC Then
			BuildCPC(xmlw)
		End If

		If RequestMsg(xmlw) = False Then
			' then we had a problem in the class.
			Return ""
		End If

		If IsCPC Then
			CloseCPC(xmlw)
		End If

		xmlw.WriteEndDocument()
		xmlw.Flush()

		mem.Position = 0
		Dim sr As New StreamReader(mem)
		rm = sr.ReadToEnd()

		xmlw.Close()
		mem.Close()

		Return rm
	End Function

	Private Sub CallResponse()
		Try
			Dim msg As XmlDocument = CPCI.ReplyXml
			Dim node As XmlNode
			'Dim attr As XmlAttribute
			Dim root As XmlNode = msg.DocumentElement

			For Each node In root.ChildNodes
				If node.Name = "NotSure" Then
					m_errmsg = node.Attributes("RejTxt").InnerText
				ElseIf node.Name = ResponseType Or ResponseType = "Batch" And node.Name = "SecDef" Then

					If Not node.Attributes("RejTxt") Is Nothing Then
						m_errmsg = node.Attributes("RejTxt").InnerText
						Exit Sub
					End If

					If Not node.Attributes("Txt") Is Nothing Then
						m_errmsg = node.Attributes("Txt").InnerText
						If m_errmsg.ToLower.StartsWith("valid") = False Then
							Exit Sub
						End If
						m_errmsg = ""
					End If

					'If IsCPC Then
					'    If Not node.Attributes("ErrCode") Is Nothing Then
					'        m_errmsg = node.Attributes("Txt").InnerText
					'        Exit Sub
					'    End If
					'End If
					ResponseParse(node)

				End If

			Next

		Catch ex As Exception

		End Try

	End Sub

	Protected Sub BuildCPC(ByRef XmlW As XmlTextWriter)
		'XmlW.WriteStartElement("CPCAPI")
		'XmlW.WriteAttributeString("v", "1.2")

		'XmlW.WriteStartElement(RequestType)
		'XmlW.WriteAttributeString("ReqID", UID)

		XmlW.WriteStartElement("FIXML")
		XmlW.WriteAttributeString("v", "5.0 SP2")
		XmlW.WriteAttributeString("s", "20090815")
		XmlW.WriteAttributeString("xv", "109")
		XmlW.WriteAttributeString("cv", "CME.0001")

		XmlW.WriteStartElement(RequestType)
		XmlW.WriteAttributeString("ReqID", UID)
		XmlW.WriteAttributeString("ReqTyp", m_reqtyp)

		' set up the request element, then end it
		RequestAttributes(XmlW)

		XmlW.WriteStartElement("Hdr")
		XmlW.WriteAttributeString("TID", "CME")
		XmlW.WriteAttributeString("TSub", "CPAPI")
		XmlW.WriteAttributeString("SID", "1A3M") 'broker specific code
		XmlW.WriteAttributeString("SSub", Globals.UserName)
		XmlW.WriteEndElement()

	End Sub

	Protected Sub CloseCPC(ByRef XmlW As XmlTextWriter)
		XmlW.WriteEndElement()
		XmlW.WriteEndElement()
	End Sub

	Protected Overridable Function RequestMsg(ByRef XmlW As XmlTextWriter) As Boolean
	End Function

	Protected Overridable Function InstrmtMsg(ByRef XmlW As XmlTextWriter) As Boolean
	End Function

	Protected Overridable Function RequestAttributes(ByRef XmlW As XmlTextWriter) As Boolean
	End Function

	Protected Overridable Sub ResponseParse(ByRef node As XmlNode)
	End Sub

	Protected Function timestamp() As String

		Dim dt As DateTime = DateTime.Now
		Dim str As String
		str = dt.ToString().Replace(":", "")

		str = str.Replace("/", "")
		str = str.Replace(" ", "")
		str = str.Replace("AM", "")
		str = str.Replace("PM", "")


		Return str
	End Function

	Protected Function getAttr(ByRef node As XmlNode, ByVal val As String) As String
		If node.Attributes(val) Is Nothing Then
			Return ""
		End If

		Return node.Attributes(val).InnerText()
	End Function
End Class
